package com.chatplus.application.common.util;


import cn.hutool.core.date.DateUtil;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;


public class IDCardUtils {

    private static final SouthernQuietLogger log = SouthernQuietLoggerFactory.getLogger(IDCardUtils.class);

    private static final String regex =
        "^[1-9]d{7}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{3}$|^[1-9]d{5}[1-9]d{3}((0d)|(1[0-2]))(([0|1|2]d)|3[0-1])d{3}([0-9]|X|x)$";

    public static final int AGE_UPPER_LIMIT = 100;

    /**
     * 15位身份证号
     */
    private static final Integer FIFTEEN_ID_CARD = 15;
    /**
     * 18位身份证号
     */
    private static final Integer EIGHTEEN_ID_CARD = 18;

    /**
     * 根据身份证号获取年龄
     *
     * @param idCard 身份证
     * @return 年龄
     */
    public static Integer getAge(String idCard) {
        Assert.notNull(idCard, "身份证不能为空");
        if (!isValid(idCard)) {
            log.message("根据身份证号获取年龄,无效的身份账号")
                .context("idCard", idCard)
                .error();

            return 0;
        }

        idCard = idCard.trim();
        //15位身份证号 例如:130503 670401 001
        if (idCard.length() == FIFTEEN_ID_CARD) {
            // 身份证上的年份(15位身份证为1980年前的)
            String birthday = "19" + idCard.substring(6, 12);
            return DateUtil.ageOfNow(DateUtil.parse(birthday));

        } else if (idCard.length() == EIGHTEEN_ID_CARD) { //18位身份证号
            // 身份证上的年份 450908 20091007 3221
            String birthday = idCard.substring(6, 14);
            return DateUtil.ageOfNow(DateUtil.parse(birthday));
        } else {
            throw new RuntimeException(String.format("不支持的身份证idCard=【%s】", idCard));
        }
    }

    /**
     * 身份证验证
     *
     * @param id 号码内容
     * @return 是否有效
     */
    public static boolean isValid(String id) {
        return StringUtils.isNotBlank(id) && !id.trim().matches(regex);
    }
}
